package com.skateboard.reelviewtest.loopviewpager

import android.util.Log
import kotlin.math.abs

/**
 * @作者： xuze
 * @时间： 2021/3/5 7:26 PM
 * @描述：
 */
@Deprecated("已废弃，请使用DataProvider2")
class DataProvider {
    /**
     * 初始数据在viewpager中的位置
     */
    companion object {
        var initialDataPositionInViewPager: Int = 100000 + 5
    }

    /**
     * 初始数据在 dataList 中的位置
     */
    private var initialDataPositionInDataList: Int = 0

    var dataList = mutableListOf<String>()

    /**
     *
     */
    init {
        dataList.addAll(createData("..."))
        dataList.add(5, "初始值")
        getInitDataIndex()
    }

    private fun createData(str: String): List<String> {
        var list = mutableListOf<String>()
        for (i in 0..9) {
            list.add("内容值：$str$i")
        }
        return list
    }

    /**
     *
     */
    var isAdd1 = false
    var isAdd2 = false

    fun getData(position: Int): String? {
        var index = adapterPosition2DataPosition(position)
        var str = ""
        if (index >= 0 && index < dataList.size) {
            str = dataList[index]
        }
        Log.e("ssss", "=====index===:$index===str:$str")
        return str
    }

    /**
     * AdapterPosition => dataPosition
     * adapter中position转化为 dataList的index
     */
    private fun adapterPosition2DataPosition(adapterPosition: Int): Int {
        var dataPosition = -1
        if (adapterPosition > initialDataPositionInViewPager) {
            var index = initialDataPositionInDataList + (adapterPosition - initialDataPositionInViewPager)
            dataPosition = if (index < dataList.size) {
                index
            } else {
                index % dataList.size
            }
        } else {
            var index = initialDataPositionInDataList - (initialDataPositionInViewPager - adapterPosition)
            dataPosition = if (index >= 0) {
                index
            } else {
                if (abs(index) % dataList.size == 0) {
                    0
                } else {
                    dataList.size - abs(index) % dataList.size
                }
            }
        }
        return dataPosition
    }

    private fun getInitDataIndex(){
        initialDataPositionInDataList = dataList.indexOf("初始值")
    }

    fun addHead(position : Int){
        var index = adapterPosition2DataPosition(position)
        if (index == 1 && !isAdd2) {
            isAdd2 = true
            for (i in 1..5) {
                dataList.add(0, "内容值：-$i")
            }
            getInitDataIndex()
        }
    }
    fun addFoot(position : Int){
        var index = adapterPosition2DataPosition(position)
        if (index == dataList.size - 2 && !isAdd1) {
            isAdd1 = true
            for (i in 10..15) {
                dataList.add("内容值：$i")
            }
        }
    }
}